import { getResponseMessage } from "@mallfoundry/client/message"
import { Staff, StaffService, StaffStatus, StaffType } from "@mallfoundry/store/staff"
import { Button, Card, Col, Divider, message as antMessage, Popconfirm, Row, Table, Tag } from "antd"
import { ColumnProps } from "antd/lib/table"
import * as _ from "lodash"
import * as React from "react"
import { Link, useLocation, useParams } from "react-router-dom"
import Page from "../../../components/page"
import { useLoading } from "../../../hooks/loading"
import { useStaffs } from "../../../hooks/staff"

interface StaffListProps {

}

export default function StaffList(props: StaffListProps) {
  const { storeId } = useParams<{ storeId: string }>()
  const location = useLocation()
  const searchParams = new URLSearchParams(location.search)
  const roleIds = searchParams.get("role_ids") as string
  const columns: ColumnProps<Staff>[] = [
    {
      title: "员工帐号",
      dataIndex: "id",
      key: "id",
      width: "15%",
    },
    {
      title: "员工姓名",
      dataIndex: "name",
      key: "name",
      width: "15%",
    },
    {
      title: "员工编号",
      dataIndex: "number",
      key: "number",
      width: "15%",
      render: (number: string) => _.isEmpty(number) ? "-" : number,
    },
    {
      title: "联系方式",
      dataIndex: "phone",
      key: "phone",
      width: "15%",
      render: (phone: string, staff) => (`+${staff.countryCode}-${phone}`),
    },
    {
      title: "角色",
      dataIndex: "roles",
      key: "roles",
      render: (roles: any) => {
        return _.chain(roles).map(role => role.name).join(", ").value()
      },
    },
    {
      title: "员工状态",
      dataIndex: "status",
      key: "status",
      align: "center",
      width: "100px",
      render: (status: StaffStatus) => {
        return status === StaffStatus.Active
          ? <Tag color="success" style={{ margin: "0" }}>已启用</Tag>
          : <Tag color="error" style={{ margin: "0" }}>停用中</Tag>
      },
    },
    {
      title: "操作",
      key: "id",
      dataIndex: "id",
      align: "right",
      width: "15%",
      render: (id, staff) => (
        <>
          {staff.type !== StaffType.Owner && <>
            {staff.status === StaffStatus.Active &&
            <Button type="link" size="small" style={{ padding: "0" }} onClick={() => inactiveStaff(id)}>停用</Button>}
            {staff.status === StaffStatus.Inactive &&
            <Button type="link" size="small" style={{ padding: "0" }} onClick={() => activeStaff(id)}>启用</Button>}
            <Divider type="vertical"/>
          </>}
          <Link to={`/stores/${storeId}/staffs/${id}`}>查看</Link>
          <Divider type="vertical"/>
          <Link to={`/stores/${storeId}/staffs/${id}/edit`}>编辑</Link>
          {staff.type !== StaffType.Owner && <>
            <Divider type="vertical"/>
            <Popconfirm placement="bottomRight" title="确定要移除该员工？" onConfirm={() => deleteStaff(id)}>
              <Button type="link" size="small" style={{ padding: "0" }}>移除</Button>
            </Popconfirm>
          </>}
        </>
      ),
    },
  ]
  const {
    elements: staffs,
    loading: staffsLoading,
    refresh: refreshStaffs,
  } = useStaffs({
    storeId, roleIds,
  })

  const [loading, setLoading] = useLoading(staffsLoading)

  function activeStaff(staffId: string) {
    setLoading(true)
    StaffService.activeStaff({ storeId, id: staffId })
      .then(() => {
        antMessage.success("启用成功")
      })
      .catch(error => {
        antMessage.error(getResponseMessage(error))
      })
      .finally(refreshStaffs)
  }

  function inactiveStaff(staffId: string) {
    setLoading(true)
    StaffService.inactiveStaff({ storeId, id: staffId })
      .then(() => {
        antMessage.success("停用成功")
      })
      .catch(error => {
        antMessage.error(getResponseMessage(error))
      })
      .finally(refreshStaffs)
  }

  function deleteStaff(staffId: string) {
    setLoading(true)
    StaffService.deleteStaff({ storeId, id: staffId })
      .then(() => {
        antMessage.success("移除成功")
      })
      .catch(error => {
        antMessage.error(getResponseMessage(error))
      })
      .finally(refreshStaffs)
  }

  return (
    <div>
      <Page.Header title="员工管理" ghost={false}/>
      <Page.Content>
        <Card>
          <Row gutter={[16, 16]}>
            <Col><Button type="primary">
              <Link to={`/stores/${storeId}/staffs/new`}>添加员工</Link></Button></Col>
          </Row>
          <Row>
            <Col span={24}>
              <Table rowKey="id" columns={columns} dataSource={staffs} loading={loading}/>
            </Col>
          </Row>
        </Card>
      </Page.Content>
    </div>
  )
}
